import { Context } from 'koa';
import { dataSource } from '../config/database';
import ProductCategoryEntity from '../entity/productCagetory.entity';
import { getIdByToken } from '../jwt/jwtService';
import result from '../vo/result';
import { ResultCode, ResultCodeMessages } from '../enums/resultCode';

const tableRepository = dataSource.getRepository(ProductCategoryEntity);
export const addProductCategory = async (ctx: Context) => {
  const token = ctx.headers['authorization'];
  const adminId = getIdByToken(token);
  const productCategory = ctx.request.body;
  productCategory.adminId = adminId;
  productCategory.baseConfig = JSON.stringify(productCategory.baseConfig);
  //查找是否存在相同name的optionalConfig，数据结构[{name:'xxx',}]
  const optionalConfig = productCategory.optionalConfig;
  const isRepeat = optionalConfig.some((item, index) => {
    return optionalConfig.findIndex((item2, index2) => {
      return item.name === item2.name && index !== index2;
    }) !== -1;
  });
  if (isRepeat) return result.fail(ResultCode.PRODUCT_CATEGORY_OPTIONAL_CONFIG_REPEAT, ResultCodeMessages[ResultCode.PRODUCT_CATEGORY_OPTIONAL_CONFIG_REPEAT]);
  productCategory.optionalConfig = JSON.stringify(optionalConfig);

  //查询是否存在相同name的分类
  const isExist = await tableRepository.findOne({
    where: {
      name: productCategory.name
    }
  });
  if (isExist) {
    return result.fail(ResultCode.PRODUCT_CATEGORY_EXIST, ResultCodeMessages[ResultCode.PRODUCT_CATEGORY_EXIST]);
  }
  await tableRepository.save(productCategory);
  return result.success('添加成功');
};

export const getProductCategoryList = async (token: string, query: any) => {
  const { pageNo = 1, pageSize = 10, ...where } = query;
  const adminId = getIdByToken(token);
  const list = (await tableRepository.find({
    where: {
      ...where,
      adminId
    },
    skip: (pageNo - 1 <= 0 ? 0 : pageNo - 1) * pageSize,
    take: pageSize,
    order: {
      createdTime: 'DESC'
    }
  }));
  list.map(item => {
    item.baseConfig = JSON.parse(item.baseConfig);
    item.optionalConfig = JSON.parse(item.optionalConfig);
    return item;
  });
  const totalCount = await tableRepository.count({
    where: {
      ...where,
      adminId
    }
  });
  return result.success({ list: list, totalCount: totalCount });
};